//
//  SHELViewController.m
//  SHEL
//
//  Created by Jennifer Guriel on 11/3/11.
//  Copyright Washington University 2011. All rights reserved.
//

#import "SHELViewController.h"
#import "JSON.h"

#define PLAYERDATA_REQ 0
#define HISTORY_REQ    1
#define TRAUMA_REQ     2

@implementation SHELViewController

-(id)init {
	[super init];
	
	tabBarController = [[UITabBarController alloc] init];
	[tabBarController.view setCenter:CGPointMake(tabBarController.view.center.x, tabBarController.view.center.y)]; // Center tab bar controller
		
	// Create two, custom UI view controllers
	players = [[PlayerViewController alloc] initWithNibName:@"Players" bundle:nil];
	playersTable = [[PlayerTableViewController alloc] initWithStyle:UITableViewStylePlain];
	
	// Create a Nav controller
	navController = [[UINavigationController alloc] init];
	[self.view addSubview:navController.view];
	[navController pushViewController:playersTable animated:NO];
	
	// Create a second Nav controller
	navController2 = [[UINavigationController alloc] init];
	[self.view addSubview:navController2.view];
	[navController2 pushViewController:players animated:NO];
	
	// Set the array of view controllers
	tabBarController.viewControllers = [NSArray arrayWithObjects:navController2, navController, nil]; 
		
	// Add the tab bar controller's view to the window
	[self.view addSubview:tabBarController.view];
		
    return self;
}


/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	[self makeRequest:nil];
	
	currentViewController = [tabBarController selectedViewController];
	
    [NSTimer scheduledTimerWithTimeInterval:.3 target:self selector:@selector(monitorTabController:) userInfo:nil repeats:YES];
}

-(void)monitorTabController:(NSTimer*) timer {
	if ([tabBarController selectedViewController] != currentViewController) {
		// Reset the previous controller 
		
		[(UINavigationController*)currentViewController popToRootViewControllerAnimated:YES];
		currentViewController = [tabBarController selectedViewController];
	}
}

-(void)makeRequest:(NSTimer*) timer {
	requestType = PLAYERDATA_REQ;
	responseData = [[NSMutableData data] retain];
	NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://radiant-meadow-2958.herokuapp.com/api/v1/player/"]];
	RMconnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

-(void)makeHistoryRequest:(int)idNum {
	requestType = HISTORY_REQ;
	responseData = [[NSMutableData data] retain];
	NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://radiant-meadow-2958.herokuapp.com/api/v1/player/%d/history",idNum]]];
	RMconnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

-(void)makeTraumaRequest:(int)idNum {
	requestType = TRAUMA_REQ;
	responseData = [[NSMutableData data] retain];
	NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://radiant-meadow-2958.herokuapp.com/api/v1/player/%d/trauma",idNum]]];
	RMconnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	[responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	players.topBarLabel.text = [NSString stringWithFormat:@"Connection failed: %@", [error description]];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	[connection release];
	
	NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
	[responseData release];

	int playerId;
	
	// If this is a player data request, then parse it
	if (requestType == PLAYERDATA_REQ)
	{
		NSArray* test = [responseString JSONValue];
		playerData = [[NSMutableArray alloc] initWithArray:test];
		requestNum = 0;
		
		// update the display of the subwindow
		[players updatePlayerData:playerData];
		[playersTable setPlayerData:playerData];
		[players setPlayerData:playerData];
		
		// pull id from player data
		playerId = [[[playerData objectAtIndex:requestNum] objectForKey:@"id"] intValue];
		
		[self makeHistoryRequest:playerId];
	}
	else if (requestType == HISTORY_REQ) {
		NSArray *playerHistory = [responseString JSONValue];
		//[players updatePlayerHistory:requestNum];
		[players addPlayerHistory:requestNum history:playerHistory];
		[playersTable addPlayerHistory:requestNum history:playerHistory];
		
		// Exit and switch to TRAUMA_REQ
		if (playerData == nil || requestNum >= [playerData count]-1) 
		{
			// Now switch to trauma requests
			requestNum = 0;
			
			// pull id from player data
			playerId = [[[playerData objectAtIndex:requestNum] objectForKey:@"id"] intValue];
			
			[self makeTraumaRequest:playerId];
		}
		else {
			requestNum++;
			
			// pull id from player data
			playerId = [[[playerData objectAtIndex:requestNum] objectForKey:@"id"] intValue];
							
			[self makeHistoryRequest:playerId];
		}
	}
	else if (requestType == TRAUMA_REQ) {
		NSArray *playerTrauma = [responseString JSONValue];
		[players addPlayerTrauma:requestNum trauma:playerTrauma];
		[playersTable addPlayerTrauma:requestNum trauma:playerTrauma];
		
		// Exit and switch back to PLAYERDATA_REQ
		if (playerData == nil || requestNum >= [playerData count]-1) 
		{
			// Make next request in 5 seconds
			requestNum = 0;
			[NSTimer scheduledTimerWithTimeInterval:5.0
											 target:self
										   selector:@selector(makeRequest:)
										   userInfo:nil
											repeats:NO];
		}
		else {
			requestNum++;
			
			// pull id from player data
			playerId = [[[playerData objectAtIndex:requestNum] objectForKey:@"id"] intValue];
			
			[self makeTraumaRequest:playerId];
		}
	}
	
	[responseString release];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
	[players release];
	[playersTable release];
	[playerData release];
	[RMconnection release];
	[navController release];
	[navController2 release];
}

@end
